<template>
  <div class="student-assignments-container">
    <el-card class="header-card">
      <div class="header-content">
        <h2>我的作业</h2>
        <div class="header-actions">
          <el-button @click="router.push('/problems')" type="success" icon="Edit">
            练习题目
          </el-button>
          <el-button @click="loadAssignments">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 作业列表 -->
    <el-card class="assignments-list">
      <template #header>
        <div class="card-header">
          <span>班级作业</span>
          <el-tag type="info">{{ assignments.length }} 个作业</el-tag>
        </div>
      </template>

      <el-table :data="assignments" v-loading="loading" style="width: 100%">
        <el-table-column prop="title" label="作业标题" min-width="200">
          <template #default="{ row }">
            <el-link type="primary" @click="viewAssignmentDetail(row)">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="class_name" label="班级" min-width="120" />
        <el-table-column prop="due_date" label="截止时间" width="180">
          <template #default="{ row }">
            <el-tag :type="isExpired(row.due_date) ? 'danger' : 'success'">
              {{ formatDate(row.due_date) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="total_score" label="总分" width="80" align="center" />
        <el-table-column prop="submission_count" label="我的提交" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="info">{{ row.submission_count || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="viewAssignmentDetail(row)">查看详情</el-button>
            <el-button size="small" type="success" @click="startAssignment(row)" v-if="!isExpired(row.due_date)">
              开始做题
            </el-button>
            <el-button size="small" type="primary" @click="submitAssignment(row)" v-if="!isExpired(row.due_date)">
              提交
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="assignments.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无作业">
          <template #description>
            <p>暂无待完成的作业</p>
            <p>您可以：</p>
            <ul style="text-align: left; display: inline-block;">
              <li>等待老师布置新的作业</li>
              <li>在题目管理页面练习编程题目</li>
              <li>查看历史提交记录</li>
            </ul>
          </template>
          <el-button type="primary" @click="router.push('/problems')">
            去练习题目
          </el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 作业详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="作业详情" width="800px">
      <div class="assignment-detail" v-if="currentAssignment">
        <div class="detail-header">
          <h3>{{ currentAssignment.title }}</h3>
          <p class="description">{{ currentAssignment.description }}</p>
          <div class="meta-info">
            <el-tag>班级: {{ currentAssignment.class_name }}</el-tag>
            <el-tag :type="isExpired(currentAssignment.due_date) ? 'danger' : 'success'">
              截止时间: {{ formatDate(currentAssignment.due_date) }}
            </el-tag>
            <el-tag type="info">总分: {{ currentAssignment.total_score }}</el-tag>
          </div>
        </div>

        <div class="problems-section">
          <h4>题目列表</h4>
          <el-table :data="currentAssignment.problems || []" style="width: 100%">
            <el-table-column prop="title" label="题目" />
            <el-table-column prop="difficulty" label="难度" width="100">
              <template #default="{ row }">
                <el-tag :type="getDifficultyType(row.difficulty)">
                  {{ row.difficulty }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button size="small" @click="goToProblem(row)">做题</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="my-submissions">
          <h4>我的提交记录</h4>
          <el-table :data="mySubmissions" style="width: 100%">
            <el-table-column prop="problem_title" label="题目" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getSubmissionStatusType(row.status)">
                  {{ getSubmissionStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="score" label="得分" width="80" align="center" />
            <el-table-column prop="submitted_at" label="提交时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.submitted_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button size="small" @click="viewSubmission(row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 提交作业对话框 -->
    <el-dialog v-model="showSubmitDialog" title="提交作业" width="800px">
      <div class="submit-content" v-if="currentAssignment">
        <div class="submit-header">
          <h4>{{ currentAssignment.title }}</h4>
          <p>请选择要提交的题目并编写代码</p>
        </div>

        <el-form :model="submitForm" ref="submitFormRef" label-width="100px">
          <el-form-item label="选择题目" prop="problem_id">
            <el-select v-model="submitForm.problem_id" placeholder="请选择题目" style="width: 100%">
              <el-option
                v-for="problem in currentAssignment.problems"
                :key="problem.id"
                :label="problem.title"
                :value="problem.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="编程语言" prop="language">
            <el-select v-model="submitForm.language" placeholder="请选择语言" style="width: 100%">
              <el-option label="Python" value="python" />
              <el-option label="Java" value="java" />
              <el-option label="C++" value="cpp" />
              <el-option label="JavaScript" value="javascript" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="代码" prop="code">
            <el-input
              v-model="submitForm.code"
              type="textarea"
              :rows="15"
              placeholder="请输入你的代码..."
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showSubmitDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAssignmentCode" :loading="submitting">提交</el-button>
      </template>
    </el-dialog>

    <!-- 查看提交详情对话框 -->
    <el-dialog v-model="showSubmissionDialog" title="提交详情" width="600px">
      <div class="submission-detail" v-if="currentSubmission">
        <div class="submission-info">
          <h4>题目: {{ currentSubmission.problem_title }}</h4>
          <p>提交时间: {{ formatDate(currentSubmission.submitted_at) }}</p>
          <p>状态: 
            <el-tag :type="getSubmissionStatusType(currentSubmission.status)">
              {{ getSubmissionStatusText(currentSubmission.status) }}
            </el-tag>
          </p>
          <p v-if="currentSubmission.score !== null">得分: {{ currentSubmission.score }}</p>
        </div>
        
        <div class="code-section">
          <h4>代码</h4>
          <el-input
            v-model="currentSubmission.code"
            type="textarea"
            :rows="10"
            readonly
          />
        </div>
        
        <div class="feedback-section" v-if="currentSubmission.feedback">
          <h4>教师反馈</h4>
          <el-input
            v-model="currentSubmission.feedback"
            type="textarea"
            :rows="4"
            readonly
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { assignmentsApi, type Assignment } from '@/api/assignments'

const router = useRouter()

// 数据
const assignments = ref<Assignment[]>([])
const mySubmissions = ref<any[]>([])
const loading = ref(false)
const submitting = ref(false)

// 对话框状态
const showDetailDialog = ref(false)
const showSubmitDialog = ref(false)
const showSubmissionDialog = ref(false)

// 表单数据
const currentAssignment = ref<Assignment | null>(null)
const currentSubmission = ref<any>(null)
const submitForm = ref({
  problem_id: 0,
  language: 'python',
  code: ''
})

// 表单引用
const submitFormRef = ref()

// 加载作业列表
const loadAssignments = async () => {
  loading.value = true
  try {
    const response = await assignmentsApi.getAssignments()
    assignments.value = response || []
  } catch (error: any) {
    console.error('加载作业列表失败:', error)
    ElMessage.error('加载作业列表失败')
    // 使用模拟数据
    assignments.value = [
      {
        id: 1,
        title: 'Python基础练习',
        description: '练习Python基础语法',
        class_name: '计算机科学1班',
        due_date: '2024-01-25 23:59:59',
        total_score: 100,
        submission_count: 0,
        status: 'active',
        created_at: '2024-01-15 10:00:00',
        problems: [
          { id: 1, title: 'Hello World', difficulty: 'easy' },
          { id: 2, title: '两数之和', difficulty: 'easy' }
        ]
      },
      {
        id: 2,
        title: '数据结构练习',
        description: '练习基本数据结构',
        class_name: '计算机科学1班',
        due_date: '2024-01-30 23:59:59',
        total_score: 150,
        submission_count: 1,
        status: 'active',
        created_at: '2024-01-20 10:00:00',
        problems: [
          { id: 3, title: '反转字符串', difficulty: 'easy' },
          { id: 4, title: '冒泡排序', difficulty: 'medium' }
        ]
      }
    ]
  } finally {
    loading.value = false
  }
}

// 查看作业详情
const viewAssignmentDetail = async (assignment: Assignment) => {
  currentAssignment.value = assignment
  showDetailDialog.value = true
  
  try {
    // 使用模拟数据
    mySubmissions.value = [
      {
        id: 1,
        problem_id: 1,
        problem_title: 'Hello World',
        language: 'python',
        status: 'accepted',
        score: 10,
        submitted_at: '2024-01-21 10:30:00'
      }
    ]
  } catch (error: any) {
    console.error('加载作业详情失败:', error)
    ElMessage.error('加载作业详情失败')
  }
}

// 提交作业
const submitAssignment = (assignment: Assignment) => {
  currentAssignment.value = assignment
  showSubmitDialog.value = true
  submitForm.value = {
    problem_id: 0,
    language: 'python',
    code: ''
  }
}

// 提交作业代码
const submitAssignmentCode = async () => {
  if (!currentAssignment.value || !submitFormRef.value) return
  
  await submitFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitting.value = true
      try {
        await assignmentsApi.submitAssignment(currentAssignment.value.id, submitForm.value)
        ElMessage.success('提交成功')
        showSubmitDialog.value = false
        viewAssignmentDetail(currentAssignment.value)
      } catch (error: any) {
        ElMessage.error(error.response?.data?.error || '提交失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 跳转到做题页面
const goToProblem = (problem: any) => {
  router.push(`/problems/${problem.id}`)
}

// 开始做作业
const startAssignment = (assignment: Assignment) => {
  if (assignment.problems && assignment.problems.length > 0) {
    // 跳转到第一个题目
    router.push(`/problems/${assignment.problems[0].id}`)
  } else {
    ElMessage.warning('该作业暂无题目')
  }
}

// 查看提交详情
const viewSubmission = (submission: any) => {
  currentSubmission.value = submission
  showSubmissionDialog.value = true
}

// 检查是否过期
const isExpired = (dueDate: string) => {
  return new Date(dueDate) < new Date()
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'active': return 'success'
    case 'expired': return 'danger'
    case 'completed': return 'info'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'active': return '活跃'
    case 'expired': return '已过期'
    case 'completed': return '已完成'
    default: return status
  }
}

// 获取提交状态类型
const getSubmissionStatusType = (status: string) => {
  switch (status) {
    case 'accepted': return 'success'
    case 'wrong_answer': return 'danger'
    case 'time_limit': return 'warning'
    case 'memory_limit': return 'warning'
    case 'compile_error': return 'danger'
    case 'pending': return 'info'
    default: return 'info'
  }
}

// 获取提交状态文本
const getSubmissionStatusText = (status: string) => {
  switch (status) {
    case 'accepted': return '通过'
    case 'wrong_answer': return '答案错误'
    case 'time_limit': return '超时'
    case 'memory_limit': return '内存超限'
    case 'compile_error': return '编译错误'
    case 'pending': return '待处理'
    default: return status
  }
}

// 获取难度类型
const getDifficultyType = (difficulty: string) => {
  switch (difficulty) {
    case 'easy': return 'success'
    case 'medium': return 'warning'
    case 'hard': return 'danger'
    default: return 'info'
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

onMounted(() => {
  loadAssignments()
})
</script>

<style scoped>
.student-assignments-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.assignment-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-header {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.detail-header h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

.description {
  margin: 0 0 15px 0;
  color: #606266;
}

.meta-info {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.problems-section,
.my-submissions {
  margin-bottom: 20px;
}

.problems-section h4,
.my-submissions h4 {
  margin-bottom: 10px;
  color: #303133;
}

.submit-content {
  max-height: 600px;
  overflow-y: auto;
}

.submit-header {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.submit-header h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.submit-header p {
  margin: 0;
  color: #606266;
}

.submission-detail {
  max-height: 600px;
  overflow-y: auto;
}

.submission-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.submission-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.submission-info p {
  margin: 5px 0;
  color: #606266;
}

.code-section,
.feedback-section {
  margin-bottom: 20px;
}

.code-section h4,
.feedback-section h4 {
  margin-bottom: 10px;
  color: #303133;
}
</style>
